<?php

namespace app\command\controller;

use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\FlowInfo;
use app\common\model\YsInfo;
use app\data\controller\Trans;
use think\Controller;

//易生
class Ys extends Controller
{
    protected $baseUrl = "./trade_log/ys/";

    //订单通知
    public function index()
    {
        $data = request()->param();
//        $data = '{"logNo":"240410081111259821","mercId":"81101002200008M","depositAmt":"0","txnTm":"20240410081105","busType":"Tran","crdFlg":"06","mercFee":"1.74","actTxnFlg":"0","txnAmt":"300.00","snNo":"68866010012348","ordNo":"qbs307202404100811047g0VVU","crdNo":"6259691111557097","agtMercId":"Y33102100021624","rateCd":"DJK","depositSts":"01","ts":"20240410081203"}';

        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        if (is_array($data)) {
            $data = $data;
        }

        if($data['busType'] == "Bind"){
            file_put_contents($this->baseUrl."data_bind_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->binds($data);
        }else if($data['busType'] == "Tran"){
            file_put_contents($this->baseUrl."data_tran_log".date("Ym").".txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->tran($data);
        }else if($data['busType'] == "TranD0"){
            $this->TranD0($data);
        }else if($data['busType'] == "simFee"){
            file_put_contents($this->baseUrl."data_flow_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->flow($data);
        }else if($data['busType'] == "TermAct"){
            file_put_contents($this->baseUrl."data_active_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->active($data);
        }else if($data['busType'] == "Merc"){
            file_put_contents($this->baseUrl."data_info_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->info($data);
        }
    }

    public function info($data){
        try {
            $info = Lib::getYsInfo($data['mercId']);
            if(!$info){
                $info = new YsInfo();
                $info->merchant_id = $data['mercId'];
                $info->merchant_name = $data['mercNm'];
                $info->corp_name = $data['corpNm'];
                $info->account_name = $data['stlAcoNm'];
                $info->save();
            }
        }catch (\Exception $e){
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
        }
    }

    public function active($data){
        $sn = $data['snNo'];
        $equip = Lib::getTerminal($sn);
        if($equip){
            try {
                $equip->active_time = strtotime($data['actTm']);
                $equip->save();
            }catch (\Exception $e){
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }
    }

    public function flow($data){
        $sn = $data['snNo'];
        $equip = Lib::getTerminal($sn);
        if($equip){
            try {
                $flow = new FlowInfo();
                $flow->sn = $sn;
                $flow->order_num = $data['logNo'];
                $flow->product_id = $equip->product_id;
                $flow->trading_time = strtotime($data['deductDate']);
                $flow->flow_money = $data['simFee'];
                $flow->how_many = $data['recNum'];
                $flow->save();

                Tools::sendGift($sn);

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }
    }

    //商户绑定通知
    public function binds($data)
    {
        $sn = $data['snNo'];
        $equip = Lib::getTerminal($sn);
        if($equip && $equip->binding_time == 0){
            try {
                $bindTime = strtotime($data['bindTm']);

                $equip->binding_time = $bindTime;
                $equip->save();

//                Tools::operateApply($sn,$equip->user_id);//客服二部，处理完到店设备，绑定后自动完成设备申请

                Tools::sendBind($equip->user_id,date("Y-m-d H:i",$bindTime));

                \app\data\controller\Binds::instance()->customer_active($sn);
            }catch (\Exception $e){
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }
    }

    public function tran($data){
        $sn = $data['snNo'];
        $equip = Lib::getTerminal($sn);
        if($equip){
            try {
                $orderNum = $data['logNo'];
                $tranAmount = $data['txnAmt'];
                $rate = ($data['mercFee'] && $data['txnAmt']) ? bcdiv((string)$data['mercFee'],(string)$tranAmount,4) : 0;
                $tradingTime = strtotime($data['txnTm']);

                $ys = new \app\common\model\transaction\Ys();
                $ys->agent_id = $data['agtMercId'];
                $ys->merchant_id = $data['mercId'];
                $ys->order_num = $orderNum;
                $ys->sn = $sn;
                $ys->trading_time = $tradingTime;
                $ys->transaction_amount = $tranAmount;
                $ys->transaction_fee = $data['mercFee'];
                $ys->transaction_rate = $rate * 100;
                $ys->transaction_type = isset($data['crdFlg']) ? $data['crdFlg'] : 0;
                $ys->ord_no = isset($data['ordNo']) ? $data['ordNo'] : 0;
                $ys->rate_type = isset($data['rateCd']) ? $data['rateCd'] : "";
                $ys->save();

                Trans::instance()->customer_month($sn,$tranAmount,$tradingTime);

                $arriveAmount = $tranAmount - $data['mercFee'];
                $tran = \app\common\model\transaction\Ys::where(['sn' => $sn])->order("trading_time asc")->find();
                if($tran){
                    $date = strtotime(date("Y-m-d",$tran->trading_time)." 23:59:59");
                    $howMany = Lib::getFlowHowMany($sn);
                    if($tradingTime > $date && $tranAmount >= 1000 && $howMany == 0){
                        $arriveAmount -= Constant::$flowYs;
                    }
                }
                Tools::sendTran($equip->user_id,$rate * 100,"易生",(string)$tranAmount,(string)$arriveAmount,date("Y-m-d H:i",$tradingTime),$sn);

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","error:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }
    }

    //更新交易快提费
    public function TranD0($data){
        $lakala = \app\common\model\transaction\Ys::where(['order_num' => $data['logNo']])->find();
        if($lakala){
            $lakala->d0_fee = $data['d0Fee'];
            $lakala->save();
        }
    }

}
